/*
 * @Descripttion:url 监控
 * @version: v1.0.0
 * @Author: lfzxs@qq.com
 * @Date: 2023-05-10 17:57:59
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2023-05-11 15:21:13
 */
package middleware

import (
	"fmt"
	"time"

	"github.com/gogf/gf/v2/net/ghttp"
	"golang.org/x/exp/slog"
)



type(

	monitorMiddleware struct {
		BaseMiddleware
		logger slog.Logger
		// 记录header信息
		showHeader bool

		
	}



	MonitorOption func(mm *monitorMiddleware)
)

func NewMonitorMiddleware(options ...MonitorOption) *monitorMiddleware{
	result := &monitorMiddleware{

	}
	result.logger = *slog.Default()
 
	for _, option := range options {
		option(result)
	}

	return result
}

func WithNotifys(notifys []NotifyFun) MonitorOption{
	return func(mm *monitorMiddleware) {
		mm.BaseMiddleware.notifys = notifys
	}
}

func WithShowHeader(showHeader bool) MonitorOption{
	return func(mm *monitorMiddleware) {
		mm.showHeader = showHeader
	}
}



func (s *monitorMiddleware) Handle(r *ghttp.Request){
	startTime := time.Now()
	r.Middleware.Next()

	// 执行时间
	elapsedTime := time.Since(startTime)
	// url 
	HttpWebURI := r.URL.Path
	HttpMethod := r.Method
	HttpHost := r.Host
	HttpRemoteAddr := r.RemoteAddr
	HttpHeadr := r.Header
	HttpParam := r.GetMapStrStr()
	HttpError := r.GetError()
	HttpProto := r.Proto
	HttpStatus := r.Response.Status
	// TODO 上传文件信息
	// TODO 事务号(当前线程号)

	
	// 参数
	// 错误码
	s.logger.Debug(fmt.Sprintf("(%s)[%d]耗时[%v],[Proto:%s][Method:%s][host:%s][HttpRemoteAddr:%s][header:%v][form:%v][error: %v]", 
			HttpWebURI,HttpStatus,elapsedTime,HttpProto,HttpMethod,HttpHost,HttpRemoteAddr,HttpHeadr,HttpParam,HttpError))

	s.BaseMiddleware.SendNotify(s,NotifyMap{"url":HttpWebURI,"elapsed":elapsedTime,"status":HttpStatus,"proto":HttpProto,"method":HttpMethod,
								"host":HttpHost,"form":HttpParam,"remoteAddr":HttpRemoteAddr,"headr":HttpHeadr,"error":HttpError})
}